package com.hanxiaozhang.advanced.no5dlx;

import com.rabbitmq.client.*;
import org.springframework.amqp.core.ExchangeTypes;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/9/23
 * @since 1.0.0
 */
public class Consumer {


    private static final String EXCHANGE_NAME = "dlx-right-exchange";

    private static final String ROUTING_KEY = "dlx.#";

    /**
     * 正常情况下的队列
     */
    private static final String QUEUE_NAME = "dlx-right-queue";

    /**
     * 死信队列的交换机
     */
    private static final String DLX_EXCHANGE_NAME = "dlx-exchange";

    /**
     * 死信队列
     */
    private static final String DLX_QUEUE_NAME = "dlx-queue";


    public static void main(String[] args) throws Exception {

        // 创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ所在主机ip或者主机名
        factory.setHost("localhost");
        // 创建一个连接
        Connection connection = factory.newConnection();
        // 创建一个频道
        Channel channel = connection.createChannel();

        // 创建交换机和队列进行绑定
        channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.TOPIC, true);

        // 处理正常的队列
        // 设置队列属性
        Map<String, Object> map = new HashMap<>(4);
        map.put("x-message-ttl", 5000);
        // 添加一个死信的属性，value：死信队列交换机的名字
        map.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);

        channel.queueDeclare(QUEUE_NAME, true, false, false, map);
        // 进行队列和交换机进行绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);


        // 处理死信的队列
        channel.exchangeDeclare(DLX_EXCHANGE_NAME, ExchangeTypes.TOPIC);
        // 声明队列
        channel.queueDeclare(DLX_QUEUE_NAME, true, false, false, null);
        // 绑定死信队列
        channel.queueBind(DLX_QUEUE_NAME, DLX_EXCHANGE_NAME, "#");
        System.out.println("Waiting for messages.");

        // 设置死信消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("死信队列接收到数据:" + new String(body));
            }
        };
        // 启动死信消费者
        channel.basicConsume(DLX_QUEUE_NAME, true, defaultConsumer);
    }

}
